#!/usr/bin/perl -w

use strict;

use CGI;
use HTML::Template;
use Encode qw/encode decode/; 
use lib("./lib");
use DB::Users;
use SimpleMailer;

use vars qw {
    $s $t $b $d $c $u $hl
};

&main();

sub main() {
	my $q = new CGI;
	my $template = "../templates/ps_save.tmpl";
	my $tmpl = new HTML::Template(filename => $template);


	$t  = $q->param("t") || "";   # title
	$s  = $q->param("s") || "";   # secure, user code
	$b  = $q->param("b") || "";   # body
	$d  = $q->param("d") || "";   # time
	$hl = $q->param("hl") || "";  # language
    $c  = $q->param("c") || "";   # comment
	$u  = $q->param("u");         # url

    unless ($u) {
        print $q->redirect("/cgi-bin/index.cgi");
        return;
    }

    &save_page();

	print  $q->header(-type => 'text/html', -charset => 'utf-8');

    print $tmpl->output;
}

sub save_page { 
    my $user_db = DB::Users->new();
    my $rh_user = $user_db->select_user_by_code($s);
    return unless ($rh_user);

    my $email = $rh_user->{mail};

    &send_mail($email); 
}

sub send_mail {
	my $email = shift;

    my $title;
    if ($c) {
        $title = "[$c]". $t;
    } else {
        $title = $t;
    }
    $title = "[kankan] " . $title;

    my $timestamp = get_timestamp();
    my $mail_body = 
qq{
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<table width="100%" border="1" cellspacing="0" cellpadding="4" bordercolor="#FFCC66" HordeCleaned="border-collapse:collapse;">
<tr bgcolor="#FFF2D9">
<td>
This is a cached page retrieved by "kankan" on $timestamp.</br>
Original: <a target="_blank" href="$u">$t</a> </br>
<font size="-1" color="gray">* This page may contains images/external files which are no longer available.</font></br>
<font size="-1" color="gray">* Page may not include frames, iframes and/or scripts.</font></br>
<font size="-1" color="gray">* "kankan" is neither affiliated with the authors of this page nor responsible for its content.</font></br>
Comment: $c
</td>
</tr>
</table>
<base href="$u">
$b
};
    SimpleMailer::send_mail($email, $title, $mail_body);
}

sub get_timestamp {
    my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst)
        = localtime(time);
    my $timestamp = sprintf("%4d-%02d-%02d %02d:%02d:%02d",
        $year+1900, $mon+1, $mday, $hour, $min, $sec);

    return $timestamp;
}

